﻿namespace CatClient.Message.Spi.Heartbeat
{
    using CatClient.Util;
    using Microsoft.VisualBasic.Devices;
    using System;
    using System.Diagnostics;
    using System.Runtime.CompilerServices;
    using System.Xml.Serialization;

    [XmlRoot("os")]
    public class OSInfo : IRefresh
    {
        private readonly Stopwatch _stopwatch = new Stopwatch();
        private readonly ComputerInfo _computer;

        public OSInfo()
        {
            this._stopwatch.Start();
            this._computer = new ComputerInfo();
            this.Name = this._computer.OSFullName;
            this.Arch = this._computer.OSPlatform;
            this.Version = this._computer.OSVersion;
            this._stopwatch.Stop();
            LogInfoWriter.GetInstance("Cat", 0, LogInfoWriter.LogLayout.Default).Info($"Heartbeat {"OSInfo"} init finish. {this._stopwatch.ElapsedMilliseconds}ms");
        }

        public void Refresh()
        {
            this._stopwatch.Restart();
            this.ProcessCount = Environment.ProcessorCount;
            this.TotalMemory = this._computer.TotalPhysicalMemory;
            this.FreeMemory = this._computer.AvailablePhysicalMemory;
            this.ProcessTime = Process.GetCurrentProcess().TotalProcessorTime.Ticks / 0x989680L;
            this._stopwatch.Stop();
            LogInfoWriter.GetInstance("Cat", 0, LogInfoWriter.LogLayout.Default).Info($"Heartbeat {"OSInfo"} refresh finish. {this._stopwatch.ElapsedMilliseconds}ms");
        }

        [XmlAttribute("name")]
        public string Name { get; set; }

        [XmlAttribute("arch")]
        public string Arch { get; set; }

        [XmlAttribute("version")]
        public string Version { get; set; }

        [XmlAttribute("available-processors")]
        public int ProcessCount { get; set; }

        [XmlAttribute("system-load-average")]
        public float AvgLoad { get; set; }

        [XmlAttribute("process-time")]
        public long ProcessTime { get; set; }

        [XmlAttribute("total-physical-memory")]
        public ulong TotalMemory { get; set; }

        [XmlAttribute("free-physical-memory")]
        public ulong FreeMemory { get; set; }

        [XmlAttribute("committed-virtual-memory")]
        public ulong CommitedMemory { get; set; }

        [XmlAttribute("total-swap-space")]
        public ulong TotalSwapSpace { get; set; }

        [XmlAttribute("free-swap-space")]
        public ulong FreeSwapSpace { get; set; }
    }
}

